package room_event

import (
	"encoding/json"
	"fmt"
	"longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/chat"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/internal/rpc/tencentim/utils"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/db_guess"
	"longmen/server/pkg/db/mysql/models/models_guess"
	"longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
	"strings"

	"github.com/spf13/cast"
	"longmen/server/pkg/common/api_models"
)

/*
查用户在某期的开奖状态
*/
func handleGuessPromptMsg(user *chat.ClientUser, groupId int, b []byte) (ret *pb.CallbackResp, err error) {
	ret = &pb.CallbackResp{}
	ret.ErrorCode = 0
	req := messages2.GuessPromptMessage{}
	err = json.Unmarshal(b, &req)
	if err != nil {
		ret.ErrorCode = 100199
		ret.ErrorInfo = fmt.Sprintf("invalid message struct, %s", err)
		//return util.CallbackFailResp(ret, ret.ErrorInfo), nil
		return utils.CallbackOkResp(""), nil
	}

	global.Log.Debugf("guessPrompt:%+v", req)
	gorder := &models_guess.GuessOrder{}
	mysql.GetXAnyParam(gorder, map[string]interface{}{"guess_id": req.GuessId, "uid": user.UserId}, true, "guessPrompt")
	global.Log.Debugf("guessPrompt order:%+v", gorder)
	if gorder.Id == 0 {
		ret.ErrorCode = 100190
		ret.ErrorInfo = fmt.Sprintf("no order err:%+v", err)
		return utils.CallbackFailResp(ret, ret.ErrorInfo), nil
	}

	oMsg := &api_models.GuessPromptMsg{}
	oMsg.Type = messages2.RoomQuizPromptMessageType
	if gorder.Status == _const.GUESS_ORDER_WIN {
		oMsg.Win = 1
		oMsg.ContinueWin = int(db_guess.CalcContinueWin(gorder.Uid))
	} else if gorder.Status == _const.GUESS_ORDER_MISSED {
		oMsg.Win = 0
	} else {
		global.Log.Info("6SendGuessPrompt9订单结果无效")
		ret.ErrorCode = 100198
		ret.ErrorInfo = fmt.Sprintf("invalid result, err:%v", err)
		//return util.CallbackFailResp(ret, ret.ErrorInfo), nil
		return utils.CallbackOkResp(""), nil
	}
	guess := cache.GetGuessRecord(gorder.GuessId)

	if guess == nil {
		global.Log.Info("6SendGuessPrompt9期次无效")
		ret.ErrorCode = 100194
		ret.ErrorInfo = fmt.Sprintf("期次无效")
		//return util.CallbackFailResp(ret, ret.ErrorInfo), nil
		return utils.CallbackOkResp(""), nil
	}
	aAnswer := strings.Split(guess.Content, "|")
	if len(aAnswer) < 2 || guess.Result <= 0 {
		global.Log.Info("开奖结果无效")
		ret.ErrorCode = 100193
		ret.ErrorInfo = fmt.Sprintf("开奖结果无效")
		//return util.CallbackFailResp(ret, ret.ErrorInfo), nil
		return utils.CallbackOkResp(""), nil
	}
	oMsg.Title = guess.Title
	oMsg.Answer = aAnswer[guess.Result-1]
	return utils.CallbackOkAndExt(oMsg, cast.ToString(groupId)), nil
}
